import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from '@devui';
import { ProductionInspectionOrder } from 'src/app/@core/data/job';

import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';

import { environment } from 'src/environments/environment';
import { SelectProductorderComponent } from '../select-productorder/select-productorder.component';
import { SelectInspectionItemComponent } from '../select-inspection-item/select-inspection-item.component';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';

@Component({
  selector: 'app-add-product-inspection',
  templateUrl: './add-product-inspection.component.html',
  styleUrls: ['./add-product-inspection.component.scss']
})
export class AddProductInspectionComponent {
  Math = Math;
    msgs: Array<Object> = [];
    UrlHead: any = environment.modifiedApiUrl;
    layoutDirection: FormLayout = FormLayout.Horizontal;
    tableWidthConfig: TableWidthConfig[] = [
      {
        field: '操作',
        width: '150px',
      },
      {
        field: '物料编码',
        width: '150px',
      },
      {
        field: '图片',
        width: '150px',
      },
      {
        field: '物料名称',
        width: '150px',
      },
      {
        field: '物料规格',
        width: '150px',
      },
    ]; //表格宽度配置
    taxRate: number = 13;
    customerContact: any;
    loadData: boolean;
    items: any[] = [
      '检验合格','检验不合格'
    ];
    item: string = '检验合格';
    productionInspectionOrder:ProductionInspectionOrder = {
      productionInspectionOrderId: 0,
      productionInspectionOrderNum: '',
      jobOrderProcessId: 0,
      jobNum: '',
      inspectionType: '',
      productNum: '',
      productName: '',
      partType: '',
      momVersion: '',
      uom: '',
      pendingInspectionQuantity: 0,
      inspectionStatus: '',
      qualifiedAmount: 0,
      unqualifiedAmount: 0,
      scrapAmount: 0,
      inspectionProjects: [
        {
          inspectionProjectName: '',
          inspectionProjectDescription: '',
          inspectionProjectUnit: '',
          attachments: []
        }
      ],
      remarks: '',
      attachments: [],
      processNum: '',
      procssName: ''
    };
    productionInspectionOrderRules: { [key: string]: DValidateRules } = {
      productionInspectionOrderNum: {
        messageShowType: 'text',
        validators: [
          { required: true, message: '*生产质检单号不能为空' },
          { minlength: 2, message: '*生产质检单号长度至少为2' },
          { maxlength: 40, message: '*生产质检单号长度至多为40' },
          { pattern: /^[^\s]*$/, message: '*生产质检单号不能包含空格' },
        ],
      },
      jobNum: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*工单号不能为空' }],
      },
      productNum: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*物料编码不能为空' }],
      },
      productName: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*物料名称不能为空' }],
      },
      partType: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*规格型号不能为空' }],
      },
      uom: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*物料单位不能为空' }],
      },
      pendingInspectionQuantity: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*建议质检数量不能为空' }],
      },
    };
    options = [
      { label: '检验', value: true },
      { label: '不检验', value: false }
    ]
    supplyContactOption = []; // 供应商联系人
    supplyContact = {}; //供应商联系人
    settlementMethodOption = []; // 结算方式
    settlementMethod = {}; //结算方式
    currencyOption = []; // 交易币种
    currency = {}; //交易币种
    collectionPeriodOption = []; // 付款账期
    collectionPeriod = {}; //付款账期
    fujianNumber: any = 0;
    defaultTaxRate = 0;
    constructor(
      private DialogService: DialogService,
      private Router: Router,
      private JobOrderService: JobOrderService,
      private CustomerService: CustomerService,
      private EncodeRulesService: EncodeRulesService,
      private ReviewFlowService: ReviewRolesService
    ) {}
    ngOnInit(): void {
      this.EncodeRulesService.GenerateWarehouseCodeRule(
        '生产质检单',
        '生产质检单'
      ).subscribe((data: any) => {
        this.productionInspectionOrder.productionInspectionOrderNum = data;
      });
      this.productionInspectionOrder.inspectionStatus = '检验合格';
    }
    showToast(type: any, summary: any, content: any) {
      switch (type) {
        default:
          this.msgs = [{ severity: type, summary: summary, content: content }];
      }
    }//提示框
    addRow() {
      this.productionInspectionOrder.inspectionProjects.push(
        {
          inspectionProjectName: '',
          inspectionProjectDescription: '',
          inspectionProjectUnit: '',
          attachments: []
        }
      );
    }//添加行
    deleteRow(index: number) {
      this.productionInspectionOrder.inspectionProjects.splice(index, 1);
      if (this.productionInspectionOrder.inspectionProjects.length == 0) {
        this.addRow();
      }
    }
    isStartApproval: boolean = false;
    isStartApprovalChange() {
      this.isStartApproval = true;
    }
    submit($event: any) {
      if ($event.valid) {
         this.JobOrderService.CreateProductionInspectionOrder(this.productionInspectionOrder).subscribe(
          (res: any) => {
            this.showToast('success', '成功', '创建成功');
            setTimeout(() => {
              this.Router.navigateByUrl('/pages/inspection/product-inspection');
            }, 1000);
          },
          (error) => {
            if (error.status == 404) {
              this.showToast('error', '失败', '服务器连接失败');
            } else {
              this.showToast('error', '失败', error.error);
            }
          }
        );
      } else {
        this.showToast('warn', '错误', '请检查表单是否填写正确');
      }
    }
    getImagesArray(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map((url) => environment.modifiedApiUrl + url);
      return urls;
    }
    cancel() {
      this.Router.navigateByUrl('/pages/inspection/product-inspection');
    }
    fujianItem(rowitem: any, dialogtype?: string) {
      const results = this.DialogService.open({
        title: '附件',
        width: '800px',
        backdropCloseable: false,
        data: {
          data: '销售附件',
          urls: rowitem.attachments,
          type: '查看'
        },
        content: AttachmentComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ]
      });
    }
    selectOrder(){
      const results = this.DialogService.open({
        id: 'Add',
        width: '1200px',
        backdropCloseable: true,
        data: {
          text: '',
        },
        title: '选择工单工序',
        content: SelectProductorderComponent,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              const row = results.modalContentInstance.CheckedRows[0];
              this.productionInspectionOrder.jobOrderProcessId = row.jobOrderProcessId;
              this.productionInspectionOrder.jobNum = row.jobOrderNum;
              this.productionInspectionOrder.productNum = row.productNum;
              this.productionInspectionOrder.productName = row.productName;
              this.productionInspectionOrder.partType = row.partType;
              this.productionInspectionOrder.momVersion = row.momVersion;
              this.productionInspectionOrder.uom = row.uom;
              this.productionInspectionOrder.pendingInspectionQuantity = row.productionQuantity;
              this.productionInspectionOrder.processNum = row.processNum;
              this.productionInspectionOrder.procssName = row.processName;

              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    // selectRequirement(dialogtype?: string) {
    //   const purchaseRequiredOrderPartIds =
    //     this.productionInspectionOrder.inspectionProjects.map(
    //       (part) => part.purchaseRequiredOrderPartId
    //     );
    //   const results = this.DialogService.open({
    //     id: 'Add',
    //     width: '1200px',
    //     maxHeight: '600px',
    //     backdropCloseable: true,
    //     data: {
    //       purchaseRequiredOrderPartIds: purchaseRequiredOrderPartIds,
    //       type: '新增',
    //     },
    //     title: '选择采购需求',
    //     content: SelectRequireComponent,
    //     dialogtype: dialogtype,
    //     onClose: () => {},
    //     buttons: [
    //       {
    //         cssClass: 'stress',
    //         text: '确定',
    //         handler: ($event: Event) => {
    //           // 现有的 inspectionProjects 数组
    //           const existingPurchaseOrderParts =
    //             this.productionInspectionOrder.inspectionProjects.filter(
    //               (item: any) => item.poPartId !== 0 && item.poPartId !== null
    //             );
    //           const newPurchaseOrderParts =
    //             results.modalContentInstance.filterRows.map((item: any) => {
    //               return {
    //                 productionInspectionOrderPartId: null, // 采购订单物料行ID
    //                 partNum: item.partNum, // 物料编号
    //                 partUOM: item.partUOM, // 物料单位
    //                 partName: item.partName, // 物料名称
    //                 description: item.description, // 物料描述
    //                 partType: item.partType, // 规格型号
    //                 image: item.image, // 图片
    //                 purchaseQuantity:
    //                   item.purchaseQuantity - item.orderedQuantity, // 采购数量
    //                 realTimeInventory: 0, // 实时库存
    //                 estimatedDeliveryDate: new Date(item.purchaseDate), //预计到货日期
    //                 priceWithTax: 0, // 单价（含税）
    //                 priceWithoutTax: 0, // 单价（不含税）
    //                 taxRate: this.defaultTaxRate, // 税率
    //                 amountWithTax: 0, // 含税金额
    //                 amountWithoutTax: 0, // 不含税金额
    //                 taxAmount: 0, // 税额
    //                 poPartId: item.propPartId, // 物料ID
    //                 receivedQuantity: 0, // 已入库数
    //                 noReceivedQuantity: 0, // 未入库数
    //                 deliveryQuantity: 0, // 已到货数
    //                 note: '', // 备注
    //                 purchasereQuireNum: item.purchaseRequiredNum, // 来源生产质检单号
    //                 poPurchaseOrderId: this.productionInspectionOrder.productionInspectionOrderId, // 采购订单ID
    //                 purchaseRequiredOrderPartId: item.purchaseRequiredOrderPartId, // 采购订物料行ID
    //                 isInspection: item.isInspection,
    //                 qrCodePath: ''
    //               };
    //             });

    //           // 合并现有的和新的 inspectionProjects 数组
    //           this.productionInspectionOrder.inspectionProjects =
    //             existingPurchaseOrderParts.concat(newPurchaseOrderParts);
    //           this.productionInspectionOrder.inspectionProjects.forEach((item) => {
    //             this.SupplierPriceService.getVaildPriceByPartId(
    //               item.poPartId
    //             ).subscribe((res: any) => {
    //               item.priceWithTax = res[0].price;
    //               this.calculateAmount(item);
    //             });
    //             this.StorehouseService.GetPartsAllInventory([
    //               item.poPartId,
    //             ]).subscribe((res: any) => {
    //               item.realTimeInventory = res[0].inventory;
    //             });
    //             this.calculateAmount(item);
    //           });
    //           if (this.productionInspectionOrder.inspectionProjects.length == 0) {
    //             this.addRow();
    //           }
    //           results.modalInstance.hide();
    //         },
    //       },
    //       {
    //         id: 'btn-cancel',
    //         cssClass: 'common',
    //         text: '取消',
    //         handler: ($event: Event) => {
    //           results.modalInstance.hide();
    //         },
    //       },
    //     ],
    //   });
    // }
    selectItem(rowItem:any,dialogtype?: string,) {
      const results = this.DialogService.open({
        id: 'Add',
        width: '1200px',
        backdropCloseable: true,
        data: {
          text: '',
        },
        title: '选择检验项目',
        content: SelectInspectionItemComponent,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
             const selectData = results.modalContentInstance.selectData;
              rowItem.inspectionProjectName = selectData.inspectionProjectName;
              rowItem.inspectionProjectDescription = selectData.inspectionProjectDescription;
              rowItem.inspectionProjectUnit = selectData.inspectionProjectUnit;
              rowItem.attachments = selectData.attachments;
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    fujian(dialogtype?: string) {
      const results = this.DialogService.open({
        title: '附件',
        width: '800px',
        backdropCloseable: false,
        data: {
          data: '销售附件',
          urls: this.productionInspectionOrder.attachments,
          type: '查看'
        },
        content: AttachmentComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ]
      });
    }
    valueChange($event:any){
      this.productionInspectionOrder.inspectionStatus = $event;
    }
}
